package com.chen.pspms.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServer {
    @Autowired
    RedisTemplate redisTemplate;

    @Bean
    @SuppressWarnings("unchecked")
    public RedisTemplate redisTemplateInit() {
        //设置序列化Key的实例化对象
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置序列化Value的实例化对象
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }

    @SuppressWarnings("unchecked")
    public boolean set(String key, Object value){
        boolean result=false;
        try{
            ValueOperations<Serializable, Object> operations=redisTemplate.opsForValue();
            operations.set(key,value);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public boolean set(String key, Object value,Long expireTime){
        boolean result=false;
        try{
            ValueOperations<Serializable, Object> operations=redisTemplate.opsForValue();
            operations.set(key,value);
            redisTemplate.expire(key,expireTime, TimeUnit.SECONDS);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public Object get(String key){
        Object object=null;
        try{
            ValueOperations<Serializable, Object> operations=redisTemplate.opsForValue();
            object=operations.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }
        return object;
    }
}
